import apicon from './apicon.js'
import apis from './api.js'
import Vue from 'vue'
// 获取php后台的系统参数 比如当时时间
const getSysInfoApi = function () {
	return new Promise(function(result){
		uni.request({
			url: apicon.host+apis.api.getSysInfoApi,
			data: {},
			method: "GET",
			header: {
				'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
				'token':  uni.getStorageSync('localtokn')?uni.getStorageSync('localtokn'):''
			},
			success: function(data) { 
				if(data.data.code == 1){
					return result(data.data.data);
				}
			},
			error: function(data) {
				// 错误信息打印
				console.log(data)
			}
		});
	})
}

// 获取商户信息接口封装(常用)
var shopIndexApiFun = function () {
	return new Promise(function(result){
		uni.request({
			url: apicon.host+apis.api.shopIndexApi,
			data: {},
			method: "GET",
			header: {
				'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
				'token':  uni.getStorageSync('localtokn')?uni.getStorageSync('localtokn'):''
			},
			success: function(data) { 
				if(data.data.code == 1){
					return result(data.data.data);
				}
			},
			error: function(data) {
				// 商户错误信息打印
				console.log(data)
			}
		});
	})
}

// 获取经纬度及城市信息
const getLocation = function(){
	return new Promise(function(result,reject){
		uni.getLocation({
			type: 'wgs84',
			geocode:true,//设置该参数为true可直接获取经纬度及城市信息
			success: function (res) {
				// console.log('当前位置的经度：' + res.longitude);
				// console.log('当前位置的纬度：' + res.latitude);
				return result(res)
			},
			fail: function (err) {
				console.log(err)
			}
		});
	})
	
}

//登录后操作
var goLogin = function(){
	if(!uni.getStorageSync('localtokn')&&!uni.getStorageSync('temporaryUserInfo')){
		uni.showToast({
			icon: 'none',
			title: '请登录后操作!'
		});
		// #ifndef MP-WEIXIN
		setTimeout(()=>{
			uni.navigateTo({
				url: '/pages_Personalcenter/Signblock/uni_Login'
			});
		},1000)
		// #endif
		return true;
	}
}
//时间戳转化为日期
var GetTime = function (timestamp) {
		let times;
		//时间戳为10位需*1000转换为毫秒，时间戳为13位的话不需乘1000
		if(timestamp&&(timestamp.toString()).length==10){
			times = Number(timestamp)*1000
		}else{
		  times = timestamp
		}
        let date = new Date(times?Number(times):(new Date().getTime()));

        let Y = date.getFullYear() + '-';

        let M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';

        let D = (date.getDate() < 10 ? '0'+ date.getDate() : date.getDate()) + ' ';

        let h = (date.getHours() < 10 ? '0'+ date.getHours() : date.getHours()) + ':';

        let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';

        let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();

        return Y+M+D+h+m+s; 
    }
// 返回上一页
const navigateBack = function(msg,url){
	uni.showToast({
		title:msg,
		icon:'none'
	})
	setTimeout(()=>{
		if(url){
			uni.reLaunch({
				url:url
			})
		}else{
			uni.navigateBack(uni.$emit("handleFun",'1')) 
		}
	},1500)
}

// 手机号正则验证
const  regPhone = /^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9]))\d{8}$/
// 身份证号验证
const regCard = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/

const regIdCard = function(idCard){
	return regCard.test(idCard)
}
// 封装压缩图片方法(仅适用于h5)
function compressed(Paths){
	var imgCompressed = new Promise(function(resolves,rejects){
		uni.getImageInfo({
			src:Paths,  
			success: function(image) { 
					    let canvasWidth = image.width //图片原始长宽
					    let canvasHeight = image.height;
					    let base = canvasWidth/canvasHeight;
					    /* debugger */
						if(canvasWidth>800){
							  canvasWidth = 800;
							  canvasHeight = Math.floor(canvasWidth/base);
						}
						let img = document.createElement('img');
						img.src = Paths; // 要压缩的图片  
						let canvas = document.createElement('canvas');
						let ctx = canvas.getContext('2d');
						canvas.width = canvasWidth;
						canvas.height = canvasHeight;
						ctx.drawImage(img, 0, 0, canvasWidth, canvasHeight);
						canvas.toBlob(function (fileSrc) {
							let imgSrc = window.URL.createObjectURL(fileSrc);//原生JS生成文件路径
							// 画布base64转图片
							var image = new Image();
							image.src = canvas.toDataURL("image/png");
							resolves(image.src)
						})
				}
		})
	})
	return imgCompressed
};

/**
 * 上传图片封装
 * chooseImage请求--携带token
 * @param {Object} url 请求链接
 * @param {Object} resolve 成功回调函数
 * @param {Object} reject 失败回调函数
 */
const uploadimg = function(num){
		var num = num?num:1
		var arr = []
		var upload = new Promise(function(resolve, reject){
		        uni.chooseImage({
					count: num, //默认9
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
		        	success: (chooseImageRes) => {
		        		const tempFilePaths = chooseImageRes.tempFilePaths;
						// H5压缩图片后在进行上传图片
						for (let i = 0; i <= tempFilePaths.length; i++) {					
						// #ifdef H5
							compressed(tempFilePaths[i]).then((imgCompressed)=>{
								uni.showLoading({
									title:'正在上传'
								})
								uni.uploadFile({
									url: apicon.host + apis.api.uploadApi, //仅为示例，非真实的接口地址
									filePath: imgCompressed,
									sourceType: ['album'],//从相册选择
									name: 'file',
									 header: {
										token: uni.getStorageSync('localtokn')
									},
									success: (uploadFileRes) => {
										uni.showToast({
											icon: 'none',
											title: JSON.parse(uploadFileRes.data).msg
										})
										if(JSON.parse(uploadFileRes.data).code==200){
											if(tempFilePaths.length>=0){
												arr.push(JSON.parse(uploadFileRes.data).data)
												if(tempFilePaths.length-1==i){
													resolve(arr)
												}
											}else{
												resolve(uploadFileRes.data.data)
											}
										}
									},
								});
							})
						// #endif
						// app小程序压缩图片后上传
						// #ifndef H5
						// uni.compressImage({  
						//   src:tempFilePaths[0],  
						//   quality: 80, 
						//   success: res => {  
							  uni.showLoading({
							  	title:'正在上传'
							  })
								uni.uploadFile({
									url: apicon.host + apis.api.uploadApi, //仅为示例，非真实的接口地址
									// filePath: res.tempFilePath,
									filePath: tempFilePaths[i],
									sourceType: ['album'],//从相册选择
									name: 'file',
									 header: {
										token: uni.getStorageSync('localtokn')
									},
									success: (uploadFileRes) => {
										uni.showToast({
											icon: 'none',
											title: JSON.parse(uploadFileRes.data).msg
										})
										if(JSON.parse(uploadFileRes.data).code==200){
											if(tempFilePaths.length>0){
												arr.push(JSON.parse(uploadFileRes.data).data)
												if(Number(tempFilePaths.length)==i+1){
													setTimeout(()=>{
														resolve(arr)
													},500)
												}
											}else{
												resolve(uploadFileRes.data.data)
											}
										}
									},
								});
						//   },  
						//   fail: (e) => {
						// 	console.log(e)  
						//   }
						// }) 
						// #endif
					}
		        	}
		        });
		    });
		    return upload;  
	}

// 上传视频封装
const uploadVideo = function(num){
	var upload = new Promise(function(resolve, reject){
		var that = this;
		uni.chooseVideo({
			count: 1,
			camera: 'front', 
			sourceType: ['camera', 'album'],
			success: function (res) {
				console.log("选择视频成功",res)
				uni.uploadFile({
					url: apicon.host + apis.api.uploadApi, //接口地址
					filePath: res.tempFilePath,
					name: 'file',
					// formData: {
					//     'user': 'test'
					// },
					header: {
						token: uni.getStorageSync('localtokn')
					},
					 success: (uploadFileRes) => {
						console.log('1张', uploadFileRes);
						let bold = JSON.parse(uploadFileRes.data)
						console.log('bold',bold)
						// var returnImage = bold.result[0].filePath + bold.result[0].fileName
						// console.log("this.returnImage", returnImage)
						resolve(bold.data.url)
					},
					error: function(data) {
						uni.showToast({
							icon: 'none',
							title: data.data.msg
						});
					}
				});
			}
		});
	})
	return upload
}
const urlTobase64 = function(url){
		return new Promise((resove,reject)=>{
			uni.getFileSystemManager().readFile({
				filePath: url, //选择图片返回的相对路径
				encoding: 'base64', //编码格式
				success: res => { //成功的回调
				console.log(res);
					let base64 = 'data:image/jpeg;base64,' + res.data //不加上这串字符，在页面无法显示的哦
					
				},fail: (e) => {
				}
			})
		})
}
// 用户登录状态
var login_status = function(){
	if(!uni.getStorageSync('localtokn')&&!uni.getStorageSync('temporaryUserInfo')){
		return 0;//未登录
	}else if(uni.getStorageSync('temporaryUserInfo')&&!uni.getStorageSync('localtokn')){
		return 1;//微信登录,未绑定手机号
	}else{
		return 2;//正式登录
	}
}


export default{
	getSysInfoApi,//获取系统信息
	getLocation,//获取经纬度
	shopIndexApiFun,//获取商户信息接口封装(常用)
	goLogin,//用户登录后在进行操作
	GetTime,//时间转化器
	navigateBack,//返回上一页封装
	regPhone,//手机号的正则验证封装
	regIdCard,//身份证号的验证
	uploadimg,//上传图片的接口封装
	uploadVideo,//上传视频封装
	urlTobase64,//小程序背景图 默认转base64
	login_status,//0未登录;1微信已登录但未绑定手机号; 2正式登录以获取到token
}
